<?php

namespace app\common\lib\line;
use GuzzleHttp\Client;
class HuobiKline implements kline
{
    public static $base_url = "https://hq.sinajs.cn/?rn=%slist=%s";   //新浪当前行情
    public static $options =[
        'verify' => false,
        'allow_redirects' => false
    ];
    public static $kline_url = "market/history/kline?period=%s&size=%d&symbol=%s";
    public static $tickers_url ="market/tickers";
    public static $_instance = null;
    public static $client =null;
    public  static function getInstance() {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    private function __construct()
    {
        self::$client = new Client(['base_uri' =>self::$base_url]);
    }
    public   function setOptions($key,$val) {
        self::$options[$key] = $val;
    }
    //通过新浪获取k线图
    public  function getList($symbols="")
    {
        $list =[];
        try {
            $response = self::$client->request('GET',self::$tickers_url,self::$options);
            $body = (string)$response->getBody();
            $data = json_decode($body,true);
            if (empty($data)||empty($data["data"])) {
                return;
            }
            $res = explode(",",$symbols);
            foreach ($res as $v) {
              if (!empty($data["data"][$v])) {
                  $list[] = array_push($data["data"][$v]);
              }
            }
            return $list;

        }catch (\Exception $e) {
            trace($e->getMessage(),'error');
            throw new \think\Exception($e, 100006);
        }

    }
    //
    public function getMinLine($min,$len,$symbol)
    {
        return $this->getKline($min,$len,$symbol);
    }

    public function getDayLine($symbol)
    {
        return $this->getKline("1day",200,$symbol);
    }

    public function getKline($scale,$size,$symbol) {
        $url =sprintf(self::$kline_url,$scale,$size,$symbol);
        try {
            $response = self::$client->request('GET', $url,self::$options);
            $body = (string)$response->getBody();
            $data = json_decode($body,true);
            if (empty($data)||empty($data["data"])) {
                return;
            }
            return $data["data"];
        } catch (\Exception $e) {
            trace($e->getMessage(),'error');
            throw new \think\Exception($e, 100006);
        }
    }
}